package com.example.example.store;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.example.domain.ChatConversations;
import com.example.example.domain.ChatMsg;
import com.example.example.mapper.ChatConverMapper;
import com.example.example.mapper.ChatMsgMapper;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class PersistentChatMemoryStore implements ChatMemoryStore {
    
    @Autowired
    private ChatMsgMapper chatMsgMapper;
    
    @Autowired
    private ChatConverMapper chatConverMapper;
    
    @Override
    public List<ChatMessage> getMessages(Object chatId) {
        // 查询指定会话ID的所有消息
        LambdaQueryWrapper<ChatMsg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMsg::getChatId, Long.valueOf(chatId.toString()))
                .orderByAsc(ChatMsg::getCreatedAt);
        
        List<ChatMsg> chatMsgs = chatMsgMapper.selectList(queryWrapper);
        List<ChatMessage> messages = new ArrayList<>();
        
        // 将数据库中的消息转换为ChatMessage对象
        for (ChatMsg chatMsg : chatMsgs) {
            ChatMessage message = switch (chatMsg.getRole()) {
                case "user" -> new UserMessage(chatMsg.getContent());
                case "assistant" -> new AiMessage(chatMsg.getContent());
                case "system" -> new SystemMessage(chatMsg.getContent());
                default -> null;
            };
            if (message != null) {
                messages.add(message);
            }
        }
        
        return messages;
    }

    @Override
    @Transactional
    public void updateMessages(Object chatId, List<ChatMessage> messages) {
        Long conversationId = Long.valueOf(chatId.toString());
        
        // 检查会话是否存在，不存在则创建新会话
        ChatConversations conversation = chatConverMapper.selectById(conversationId);
        if (conversation == null) {
            conversation = new ChatConversations();
            conversation.setId(conversationId);
            conversation.setTitle("New Conversation");
            conversation.setCreatedAt(new Date());
            conversation.setUpdatedAt(new Date());
            chatConverMapper.insert(conversation);
        } else {
            // 更新会话的更新时间
            conversation.setUpdatedAt(new Date());
            chatConverMapper.updateById(conversation);
        }
        
        // 删除原有消息
        LambdaQueryWrapper<ChatMsg> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(ChatMsg::getChatId, conversationId);
        chatMsgMapper.delete(deleteWrapper);
        
        // 保存新消息
        for (ChatMessage message : messages) {
            ChatMsg chatMsg = new ChatMsg();
            chatMsg.setChatId(conversationId);
            chatMsg.setCreatedAt(new Date());
            
            if (message instanceof UserMessage) {
                chatMsg.setRole("user");
                chatMsg.setContent(((UserMessage) message).singleText());
            } else if (message instanceof AiMessage) {
                chatMsg.setRole("assistant");
                chatMsg.setContent(((AiMessage) message).text());
            } else if (message instanceof SystemMessage) {
                chatMsg.setRole("system");
                chatMsg.setContent(((SystemMessage) message).text());
            }
            
            chatMsgMapper.insert(chatMsg);
        }
    }

    @Override
    @Transactional
    public void deleteMessages(Object chatId) {
        // 删除指定会话ID的所有消息
        LambdaQueryWrapper<ChatMsg> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(ChatMsg::getChatId, Long.valueOf(chatId.toString()));
        chatMsgMapper.delete(deleteWrapper);
        
        // 删除会话记录
        chatConverMapper.deleteById(Long.valueOf(chatId.toString()));
    }
}
